package com.xiaomi.web.handlers;

import com.xiaomi.domain.OrdersEntity;
import com.xiaomi.domain.TrolleyEntity;
import com.xiaomi.domain.UserEntity;
import com.xiaomi.service.TrolleyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class TrolleyHandler {

    @Autowired
    private OrdersEntity ordersEntity;

    @Autowired
    private TrolleyService trolleyService;

    @RequestMapping(name = "购物车展示",path = "trolley")
    public String Shoppingcartdisplay(Integer uid,Model model){
        List<TrolleyEntity> shoppingcartdisplay = trolleyService.Shoppingcartdisplay(uid);
        model.addAttribute("trolleys",shoppingcartdisplay);
        return "trolley";
    }
    @RequestMapping(name = "增加或减少数量",path = "addOrDeleteNumber")
    public String addOrDeleteNumber(Integer tid,Integer number,Integer uid){
        trolleyService.addOrDeleteNumber(tid,number);
        return "redirect:/trolley?uid="+uid;
    }
    @RequestMapping(name = "删除一条购物车的信息",path = "deleteTrolley")
    public String deleteTrolley(Integer tid, HttpSession session){
        UserEntity user =(UserEntity)session.getAttribute("user");
        trolleyService.deleteTrolley(tid);

        return "redirect:/trolley?uid="+user.getUid();
    }
    @RequestMapping(name = "生成订单和删除购物车对应信息",path = "createOrders")
    public String createOrders(double sumPrice,Integer goodsCount,Integer uid,Model model,HttpSession session) throws ParseException {
        UserEntity user = (UserEntity) session.getAttribute("user");
        ordersEntity = trolleyService.createOrders(sumPrice,goodsCount,user);
        model.addAttribute("order",ordersEntity);
        System.out.println("删除的对应uid:"+uid);
        trolleyService.deleteByuid(uid);

      return "order";
    }

    @RequestMapping(name = "查询购物车商品种类", path = "selectTrolleyCount")
    @ResponseBody
    public int selectTrolleyCount(Integer uid){
        System.out.println(uid);
        int count =trolleyService.selectTrolleyCount(uid);
        System.out.println(count);
        return count;
    }

    @RequestMapping(name = "增加商品进购物车",path = "addGoodInCart")
    public String addGoodInCart(HttpSession session,Integer gid){
        UserEntity user = (UserEntity)session.getAttribute("user");
        Integer uid = user.getUid();
        trolleyService.addGoodInCart(uid,gid);
        return "redirect:/trolley?uid="+uid;
    }
}
